package cn.hfatec.shms.web.xc.xcOpen.service;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.web.xc.xcWeek.model.XcWeek;
import cn.hfatec.shms.web.xc.xcWeek.model.XcWeekParams;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.xc.xcOpen.model.XcOpen;
import cn.hfatec.shms.web.xc.xcOpen.dao.XcOpenDao;
import cn.hfatec.shms.web.xc.xcOpen.model.XcOpenParams;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author hfatec
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Service("XcOpenService")
public class XcOpenService {

    public static final String BEAN_ID = "XcOpenService";

    //注入Dao层
    @Resource(name = "XcOpenDao")
    private XcOpenDao xcOpenDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     *
     * 查询数据
     *
     * @param xcOpenParams
     * @param page
     *
     */
    @Transactional
    public Table queryXcOpenTable(XcOpenParams xcOpenParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        String bzStart = null;
        if ((xcOpenParams.getRiqiStart() == null) || (xcOpenParams.getRiqiStart().isEmpty())) {
            bzStart = getBzstart();
            xcOpenParams.setRiqiStart(bzStart);
        } else {
            bzStart = xcOpenParams.getRiqiStart();
        }

        if ((xcOpenParams.getRiqiEnd() == null) || (xcOpenParams.getRiqiEnd().isEmpty())) {
          String  riqiend = getBzend(bzStart);
            xcOpenParams.setRiqiEnd(riqiend);
        }

        params.put("params", xcOpenParams);
        return baseDao.queryTableByPage("queryXcOpen", params, page);
    }

    public String getBzstart() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        cal.add(Calendar.DATE, -1);
        String bzstart = df.format(cal.getTime());
        return bzstart;
    }

    public String getBzend(String bzStart) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate = null;
        String bzend = null;
        try {
            myDate = formatter.parse(bzStart);
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            c.add(Calendar.DATE, 6);
            myDate = c.getTime();
            bzend = formatter.format(myDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return bzend;
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(XcOpenParams xcOpenParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = xcOpenDao.queryXcOpen(xcOpenParams);
            List nameList = new ArrayList();
            nameList.add("操作员");
            nameList.add("开单人");
            nameList.add("F0");
            nameList.add("F501");
            nameList.add("F1501");
            nameList.add("F2901");
            nameList.add("应开金额");
            nameList.add("人数小计");
            nameList.add("空人数");
            nameList.add("自测人数");
            nameList.add("A人数");
            nameList.add("A2人数");
            nameList.add("B人数");
            nameList.add("C人数");
            nameList.add("D人数");
            nameList.add("BCD金额");
            nameList.add("BCD小计");
            nameList.add("开单合格率");
            nameList.add("开单率");
            nameList.add("损失金额");
            nameList.add("损失金额占比");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> vipTypeList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> overdueTypeList = CodeInfoCache.getCodeInfo(CodeType.OVERDUE_TYPE);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("开单合格率");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        XcOpen xcOpen = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            xcOpen = (XcOpen) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (xcOpen.getOperator() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(xcOpen.getOperator());
            }
            if (xcOpen.getPerson() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(xcOpen.getPerson());
            }
            if (xcOpen.getF0() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(xcOpen.getF0());
            }

            if (xcOpen.getF501() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(xcOpen.getF501());
            }
            if (xcOpen.getF1501() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(xcOpen.getF1501());
            }
            if (xcOpen.getF2901() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(xcOpen.getF2901());
            }
            if (xcOpen.getOpenMoney() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(xcOpen.getOpenMoney());
            }
            if (xcOpen.getOpenSum() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(xcOpen.getOpenSum());
            }
            if (xcOpen.getEmptyNumber() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(xcOpen.getEmptyNumber());
            }
            if (xcOpen.getHealthNum() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(xcOpen.getHealthNum());
            }
            if (xcOpen.getANum() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(xcOpen.getANum());
            }
            if (xcOpen.getA2Num() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(xcOpen.getA2Num());
            }
            if (xcOpen.getBNum() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                row.createCell((short) 12).setCellValue(xcOpen.getBNum());
            }
            if (xcOpen.getCNum() == null) {
                row.createCell((short) 13).setCellValue("");
            } else {
                row.createCell((short) 13).setCellValue(xcOpen.getCNum());
            }
            if (xcOpen.getDNum() == null) {
                row.createCell((short) 14).setCellValue("");
            } else {
                row.createCell((short) 14).setCellValue(xcOpen.getDNum());
            }
            if (xcOpen.getBcdMoney() == null) {
                row.createCell((short) 15).setCellValue("");
            } else {
                row.createCell((short) 15).setCellValue(xcOpen.getBcdMoney());
            }
            if (xcOpen.getBcdSum() == null) {
                row.createCell((short) 16).setCellValue("");
            } else {
                row.createCell((short) 16).setCellValue(xcOpen.getBcdSum());
            }
            if (xcOpen.getOpenPass() == null) {
                row.createCell((short) 17).setCellValue("");
            } else {
                row.createCell((short) 17).setCellValue(xcOpen.getOpenPass());
            }
            if (xcOpen.getOpenRate() == null) {
                row.createCell((short) 18).setCellValue("");
            } else {
                row.createCell((short) 18).setCellValue(xcOpen.getOpenRate());
            }
            if (xcOpen.getLossesMoney() == null) {
                row.createCell((short) 19).setCellValue("");
            } else {
                row.createCell((short) 19).setCellValue(xcOpen.getLossesMoney());
            }
            if (xcOpen.getLossesRate() == null) {
                row.createCell((short) 20).setCellValue("");
            } else {
                row.createCell((short) 20).setCellValue(xcOpen.getLossesRate());
            }

        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }

}